<template>
  <div v-if="dialogVisible">
    <el-dialog title="批量导入" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false" :before-close="close">
      <div>
        <el-form ref="RefForm" :model="formData" label-width="100px" :validate-on-rule-change="false" status-icon>
          <el-form-item label="必填项:" prop="jobTitle">{{ required }}</el-form-item>
          <el-form-item v-if="pageName=='position'" label="要求和规则:" prop="jobCode">
            <div>{{ requirementRuleOne }}</div>
            <div>{{ requirementRuleTwo }}</div>
            <div>{{ requirementRuleThree }}</div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-upload
          ref="imgRef"
          style="display: inline-block;margin: 0 10px;"
          class="upload-demo"
          action
          :http-request="uploadFile"
          :headers="{
            Authorization: `Bearer ${$store.getters.token}`
          }"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :show-file-list="false"
        >
          <el-button icon="el-icon-folder-add" type="primary">选择文件</el-button>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import dialogEditMixin from '@/mixins/dialogEdit'
  import { importEmployee, importCar } from '@/api/api'
  export default {
    mixins: [dialogEditMixin],
    data() {
      return {
        formData: {},
        pageName: '', // 哪个页面的导入
        requirementRuleOne: '1.上传的文件只能是 xlsx 或 xls 类型。', // 要求和规则
        requirementRuleTwo: '2.表格中【部门，职位，工种】输入内容必须在系统中已有的内容。',
        requirementRuleThree: '3.表格中员工编码与系统中存在重复，系统中资料将被覆盖。',
        required: '员工编号、姓名' // 必填项
      }
    },
    methods: {
      setPageName(value) {
        this.pageName = value
        if (value === 'position') {
          this.required = '员工编号、姓名' // 必填项
        } else if (value === 'car') {
          this.required = '车辆类型，车牌号' // 必填项
        }
      },
      // 上传成功
      handleAvatarSuccess(res, file, fileList) {
        if (!res) {
          this.$message.error('上传失败，请重试！')
          this.$refs.imgRef.clearFiles()
          return
        }
        if (res.code === 200) {
          if (res.data == false) {
            const h = this.$createElement

            let newDatas = []
            let data = res.message.split('|')
            for (let i in data) {
              newDatas.push(h('p', null, data[i]))
            }
            this.$notify({
              title: '导入错误',
              message: h('div', null, newDatas),
              type: 'error',
              duration: 0
            })
          } else {
            this.$message.success(res.message)
            this.dialogVisible = false
            this.$emit('success')
          }
          this.$refs.imgRef.clearFiles()
        }
      },
      // 上传前
      beforeAvatarUpload(file) {
        const isJPG = (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (file.type === 'application/vnd.ms-excel')
        // const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传的文件只能是 xlsx 或 xls 类型!')
        }
        // if (!isLt2M) {
        //   this.$message.error("上传头像图片大小不能超过 2MB!")
        // }
        return isJPG
        // && isLt2M
      },
      async uploadFile(value) {
        try {
          let pat = value.file.path
          // let pat = 'C:/Users/Administrator/Desktop/employees.xlsx'
          let res = null
          if (this.pageName === 'position') {
            res = await importEmployee(pat)
          } else if (this.pageName === 'car') {
            res = await importCar(pat)
          }


          if (!res) {
            this.$message.error('上传失败，请稍后重试！')
            this.$refs.imgRef.clearFiles()
            return
          }
          if (res.code === 200) {
            if (res.data == false) {
              const h = this.$createElement

              let newDatas = []
              let data = res.message.split('|')
              for (let i in data) {
                newDatas.push(h('p', null, data[i]))
              }
              this.$notify({
                title: '导入错误',
                message: h('div', null, newDatas),
                type: 'error',
                duration: 0
              })
            } else {
              this.$message.success(res.message)
              this.dialogVisible = false
              this.$emit('success')
            }
            this.$refs.imgRef.clearFiles()
          }
        } catch (err) {
          let errtwo = err
        }
      },
      resetFormData() {
        this.formData = {
        }
      },
    }
  }
</script>

<style lang="scss" scoped></style>
